package com.example.web.websystem.ann;

import com.example.web.websystem.controller.vo.TableDataVO;
import com.example.web.websystem.response.CommonReturnData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by YangGang on 2021/8/17 11:01。
 */
@Aspect
@Component
public class AnnPagingAspect {
    private static final int DEFAULT_PAGE_NUM = 1;
    private static final int DEFAULT_PAGE_SIZE = 10;

    @Around("@annotation(annPaging)")
    public Object around(ProceedingJoinPoint joinPoint, AnnPaging annPaging) throws Throwable {
        //方法之前执行...
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        //分页
        Page page = PageHelper.startPage(
                pageNum == null ? DEFAULT_PAGE_NUM : Integer.parseInt(pageNum),
                pageSize == null ? DEFAULT_PAGE_SIZE : Integer.parseInt(pageSize)
        );
        //执行方法
        CommonReturnData proceed = (CommonReturnData) joinPoint.proceed();
        //方法之后执行...
        TableDataVO vo=new TableDataVO();
        vo.setTotal(page.getTotal());
        vo.setList(page.getResult());
        proceed.setData(vo);

        return proceed;
    }


}
